package ren.steve.system.utils;

import ren.steve.model.system.bean.SystemDept;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description: 处理部门结构化数据
 * @Date: Created in 2024/2/13 15:52
 */

public class DeptNodeHelper<T> {

  public static List<SystemDept> findRootDept (List<SystemDept> depts) {
    List<SystemDept> root = new ArrayList<>();
    for (SystemDept dept : depts) {
      if (dept.getParentId() == 0) {
        root.add(dept);
      }
    }
    return root;
  }

  public static List<SystemDept> findChildDept (List<SystemDept> depts) {
    List<SystemDept> children = new ArrayList<>();
    for (SystemDept dept : depts) {
      if (dept.getParentId() != 0) {
        children.add(dept);
      }
    }
    return children;
  }

  public static SystemDept findParentDept(List<SystemDept> depts, Integer id) {
    SystemDept result = null;
    for (SystemDept dept : depts) {
      if (Objects.equals(dept.getId(), id.toString())) {
        result = dept;
      } else {
        if (dept.getChildren() != null) {
          result = findParentDept(dept.getChildren(), id);
        }
      }
    }
    return result;
  }

  public static List<SystemDept> buildDepts (List<SystemDept> roots, List<SystemDept> depts) {
    for (SystemDept dept : depts) {
      if (dept.getParentId() != 0) {
        SystemDept result = DeptNodeHelper.findParentDept(roots, dept.getParentId());
        if (result != null) {
          if (result.getChildren() == null) {
            result.setChildren(new ArrayList<>());
          }
          result.getChildren().add(dept);
        }
      }
    }
    return roots;
  }
}
